package com.example.concurrentprogramming8016.reetrantlock;

import lombok.extern.slf4j.Slf4j;

import java.sql.Time;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author liyanhao
 * @Date 2023-01-05 12:41
 */
@Slf4j
public class ConditionTest {
    public static void main(String[] args) {
        ReentrantLock reentrantLock = new ReentrantLock();
        Condition condition = reentrantLock.newCondition();
        new Thread(() -> {
            reentrantLock.lock();
            try {
                log.debug(Thread.currentThread().getName() + " 开始处理任务");
                //休眠直接到别唤醒 并且此时会释放锁
                condition.await();
                log.debug(Thread.currentThread().getName() + " 结束处理任务");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                reentrantLock.unlock();
            }
        }, "thread-1").start();

        new Thread(() -> {
            reentrantLock.lock();
            log.debug(Thread.currentThread().getName()+" 开始处理任务");
            try {
                TimeUnit.SECONDS.sleep(2);
                //唤醒一个等待的线程 唤醒thread-1的await 但是不会释放锁资源  所以唤醒的线程会等此线程执行结束后才唤醒
                condition.signal();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }finally {
                try {
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                reentrantLock.unlock();
            }
            log.debug(Thread.currentThread().getName()+" 结束处理任务");

        }, "thread-2").start();

    }
}
